package me.shibor.study.quartz.demo;

import java.util.Date;
import java.util.List;

import org.quartz.CronScheduleBuilder;
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.JobKey;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.Trigger;
import org.quartz.TriggerBuilder;
import org.quartz.impl.StdSchedulerFactory;
import org.quartz.impl.matchers.GroupMatcher;

import me.shibor.study.quartz.job.JobA;
import me.shibor.study.quartz.job.JobB;
import me.shibor.study.quartz.job.JobC;

public class MultiJobExample {

	public static void main(String[] args) throws SchedulerException {

		JobKey jobKeyA = new JobKey("JobA", "group1");
		JobDetail jobA = JobBuilder.newJob(JobA.class).withIdentity(jobKeyA).build();

		JobKey jobKeyB = new JobKey("JobB", "group2");
		JobDetail jobB = JobBuilder.newJob(JobB.class).withIdentity(jobKeyB).build();

		JobKey jobKeyC = new JobKey("JobC", "group3");
		JobDetail jobC = JobBuilder.newJob(JobC.class).withIdentity(jobKeyC).build();

		CronScheduleBuilder cronSchedule = CronScheduleBuilder.cronSchedule("0/20 * * * * ?");

		// StdSchedulerFactory.getDefaultScheduler().

		Trigger trigger1 = TriggerBuilder.newTrigger().withIdentity("trigger1", "trigger group1")
				.withSchedule(cronSchedule).build();
		Trigger trigger2 = TriggerBuilder.newTrigger().withIdentity("trigger2", "trigger group2")
				.withSchedule(cronSchedule).build();
		Trigger trigger3 = TriggerBuilder.newTrigger().withIdentity("trigger3", "trigger group1")
				.withSchedule(cronSchedule).build();

		// Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();
		Scheduler scheduler = new StdSchedulerFactory().getScheduler();

		scheduler.scheduleJob(jobA, trigger1);
		scheduler.scheduleJob(jobB, trigger2);
		scheduler.scheduleJob(jobC, trigger3);
		scheduler.start();

		for (String groupName : scheduler.getJobGroupNames()) {

			for (JobKey jobKey : scheduler.getJobKeys(GroupMatcher.jobGroupEquals(groupName))) {

				String jobName = jobKey.getName();
				String jobGroup = jobKey.getGroup();

				// get job's trigger
				@SuppressWarnings("unchecked")
				List<Trigger> triggers = (List<Trigger>) scheduler.getTriggersOfJob(jobKey);
				Date nextFireTime = triggers.get(0).getNextFireTime();

				System.out.println("[jobName] : " + jobName + " [groupName] : " + jobGroup + " - " + nextFireTime);

			}

		}
	}
}
